package org.deltaset.secured.user;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.ManagedBean;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.inject.Inject;
import org.deltaset.faces.FacesUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.web.context.WebApplicationContext;

/**
 *
 * @author dmakariev
 */
@ManagedBean
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class PreferencesBean implements Serializable {

    private static final long serialVersionUID = 5715138209989353221L;
    private static final Logger logger = Logger.getLogger(PreferencesBean.class.getName());
    private static final String[] supportedShowPagers = new String[]{"top", "bottom", "both"};
    private static final String[] supportedFieldsetPositions = new String[]{"left", "right", "top-left", "top-right"};
    private static final String[] supportedLayouts = new String[]{"right", "left"};
    private static final String[] supportedThemes = FacesUtils.loadThemes();
    private static final String[] supportedViewTypes = new String[]{"list", "view", "view-table"};
    private static final String[] supportedUiStyles = new String[]{"internal", "flow"};
    private Locale currentLocale;
    private final PreferencesRepository preferencesRepository;
    private final UserContextBuilder userContextBuilder;
    private final UserContext userContext;

    @Inject
    public PreferencesBean(PreferencesRepository preferencesRepository) {
        this.preferencesRepository = preferencesRepository;
        this.userContext = preferencesRepository.loadUserContext();
        this.userContextBuilder = UserContext.from(userContext);

//        this.currentLocale = FacesContext.getCurrentInstance().getApplication().getDefaultLocale();
//        this.layoutName = "left";
//        this.themeName = "start";
//        this.currentLocale = FacesContext.getCurrentInstance().getApplication().getDefaultLocale();
//        this.layoutName = "left";
//        this.themeName = "start";
    }

    //private UserContext uc;
    public void saveUserContextListener(javax.faces.event.ActionEvent e) {
        saveUserContext();
    }

    public void saveUserContext() {
        preferencesRepository.saveUserContext(userContextBuilder.build());
        final Flash flash = FacesContext.getCurrentInstance().getExternalContext().getFlash();
        flash.keep("openpref");
    }

    private UserContext getUserContext() {
        return userContext;
    }

    public boolean getHasValidationErrors() {
        return FacesMessage.SEVERITY_ERROR.equals(FacesContext.getCurrentInstance().getMaximumSeverity());
    }

    public Locale getCurrentLocale() {
        if (null == currentLocale) {
            currentLocale = new Locale(getUserContext().getLocale());
        }
        return currentLocale;
    }

    public List<Locale> getSupportedLocales() {

        List<Locale> locales = new ArrayList<Locale>();
        for (Iterator<Locale> it = FacesContext.getCurrentInstance().getApplication().getSupportedLocales(); it.hasNext();) {
            Locale loc = it.next();
            locales.add(loc);
        }
        return locales;
    }

    public void setCurrentLocaleLanguage(final String language) {
        userContextBuilder.locale(language);
        //preferencesRepository.saveUserContext( UserContext.from(getUserContext()).locale(language).build() );
        this.currentLocale = new Locale(language);
        // FacesContext.getCurrentInstance().getViewRoot().setLocale(this.currentLocale);
    }

    public boolean getIsUserLoggedIn() {
        return isUserInRole("ROLE_USER") || isUserInRole("ROLE_ADMIN");
    }

    protected boolean isUserInRole(final String role) {
        return true;
    }

    public String getDateFormat() {
        return getUserContext().getDateFormat();
    }

    public void setDateFormat(String dateFormat) {
        final List<FacesMessage> fml = FacesContext.getCurrentInstance().getMessageList();
        for (Iterator<FacesMessage> it = fml.iterator(); it.hasNext();) {
            final FacesMessage facesMessage = it.next();
            logger.log(Level.INFO, "facesMessage={0} summary={1}", new Object[]{facesMessage.getDetail(), facesMessage.getSummary()});
        }
        userContextBuilder.dateFormat(dateFormat);
    }

    /**
     * @return the themeName
     */
    public String getThemeName() {
        return getUserContext().getThemeName();
        //return themeName;
    }

    /**
     * @param themeName the themeName to set
     */
    public void setThemeName(String themeName) {
        userContextBuilder.themeName(themeName);
    }

    /*
    private static final String[] supportedThemes = new String[]{
    "black-tie",
    "blitzer",
    "cupertino",
    "dark-hive",
    "dot-luv",
    "eggplant",
    "excite-bike",
    "flick",
    "hot-sneaks",
    "humanity",
    "le-frog",
    "mint-choc",
    "overcast",
    "pepper-grinder",
    "redmond",
    "smoothness",
    "south-street",
    "start",
    "sunny",
    "swanky-purse",
    "trontastic",
    "ui-darkness",
    "ui-lightness",
    "vader"
    };
     */
    /**
     * @return the supportedThemes
     */
    public String[] getSupportedThemes() {
        return supportedThemes;
    }

    /**
     * @return the layoutName
     */
    public String getLayoutName() {
        return getUserContext().getLayoutName();
    }

    /**
     * @param layoutName the layoutName to set
     */
    public void setLayoutName(String layoutName) {
        userContextBuilder.layoutName(layoutName);
    }

    /**
     * @return the supportedLayouts
     */
    public String[] getSupportedLayouts() {
        return supportedLayouts;
    }

    public String getUiStyle() {
        return getUserContext().getUiStyle();
    }

    public void setUiStyle(final String uiStyle) {
        userContextBuilder.uiStyle(uiStyle);
    }

    public String getViewType() {
        return getUserContext().getViewType();
    }

    public void setViewType(String viewType) {
        userContextBuilder.viewType(viewType);
    }

    public String[] getSupportedViewTypes() {
        return supportedViewTypes;
    }

    public String[] getSupportedUiStyles() {
        return supportedUiStyles;
    }

    public String getShowPager() {
        return getUserContext().getShowPager();
    }

    public void setShowPager(String showpager) {
        userContextBuilder.showPager(showpager);
    }

    public String getFieldsetPosition() {
        return getUserContext().getFieldsetPosition();
    }

    public void setFieldsetPosition(String fieldsetposition) {
        userContextBuilder.fieldsetPosition(fieldsetposition);
    }

    /**
     * @return the supportedShowPagers
     */
    public String[] getSupportedShowPagers() {
        return supportedShowPagers;
    }

    /**
     * @return the supportedFieldsetPositions
     */
    public String[] getSupportedFieldsetPositions() {
        return supportedFieldsetPositions;
    }

    public String getUserAgent() {
        //FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap()
       /* String accept = request.getHeader("accept");
        String user_agent = request.getHeader("user-agent");
        String accept_charset = request.getHeader("accept-charset");
        String accept_language = request.getHeader("accept-language");
        String x_wap_profile = request.getHeader("x-wap-profile");
        String profile = request.getHeader("profile");*/
        String[] headerNames = new String[]{
            "accept", "user-agent", "accept-charset", "accept-language", "x-wap-profile", "profile"
        };
        String result = "";
        for (String string : headerNames) {
            result += string + "=" + FacesUtils.getHeader(string) + "<br/>";
        }
        return result;
    }

    //TODO:check usage of flash scope
    public void open() {
        final Flash flash = FacesContext.getCurrentInstance().getExternalContext().getFlash();
        flash.putNow("openpref", true);
        flash.keep("openpref");
    }

    public boolean getOpenFlag() {
        final Flash flash = FacesContext.getCurrentInstance().getExternalContext().getFlash();
        return null == flash.get("openpref") ? Boolean.FALSE : (Boolean) flash.get("openpref");
    }
}
